import React, { useState } from "react";

function FileUpload() {
  const [file, setFile] = useState(null);

  const handleFileChange = (e) => {
    setFile(e.target.files[0]);
  };

  const uploadFileInChunks = async () => {
    if (!file) return;

    const chunkSize = 1 * 1024 * 1024; // 每块大小为 1MB
    const totalChunks = Math.ceil(file.size / chunkSize);
    const fileName = file.name;

    for (let i = 0; i < totalChunks; i++) {
      // 使用file.slice方法分块
      // 关键步骤
      const chunk = file.slice(i * chunkSize, (i + 1) * chunkSize);
      // 调用接口上传分段的文件
      // 这种是等待这次传输完成之后才会传输下一次
      await uploadChunk(chunk, i, fileName, totalChunks);
      console.log(`Uploaded chunk ${i + 1}/${totalChunks}`);
    }

    // 所有块上传完成后通知服务器合并
    await notifyServerToMerge(fileName, totalChunks);
    alert("File uploaded successfully!");
  };

  const uploadFileInChunksAll = async () => {
    let arr = [];

    const maxChunkSize = 1 * 1024 * 1024;
    const chunksTotal = Math.ceil(file.size / maxChunkSize);
    const fileName = file.name;

    for (let i = 0; i < chunksTotal; i++) {
      const chunk = file.slice(i * maxChunkSize, (i + 1) * maxChunkSize);
      arr.push(uploadChunk(chunk, i, fileName, chunksTotal));
    }

    await Promise.all(arr);
    await notifyServerToMerge(fileName, chunksTotal);
    alert("File uploaded successfully");
  }

  const uploadChunk = async (chunk, index, fileName, totalChunks) => {
    const formData = new FormData();
    formData.append("file", chunk);
    formData.append("fileName", fileName);
    formData.append("chunkIndex", index);
    formData.append("totalChunks", totalChunks);

    await fetch("http://localhost:3000/upload-chunk", {
      method: "POST",
      body: formData,
    });
  };

  const notifyServerToMerge = async (fileName, totalChunks) => {
    await fetch("http://localhost:3000/merge-file", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        fileName,
        totalChunks,
      }),
    });
  };

  return (
    <div>
      <input type="file" onChange={handleFileChange} />
      <button onClick={uploadFileInChunks}>Upload</button><br />
      <button onClick={uploadFileInChunksAll}>Merge</button>
    </div>
  );
}

export default FileUpload;